﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TestStepsEditor.Actions;
using TestStepsEditor.Viewers.Data;

namespace TestStepsEditor.Forms
{
    public partial class HiddenMainForm : Form
    {
        List<MainForm> Forms = new List<MainForm>();
        private SharedData Data;

        public HiddenMainForm()
        {
            InitializeComponent();
            MainForm form = new MainForm();
            InitForm(form);
            form.Show();
        }
        
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            Hide();
        }
        
        void InitForm (MainForm form)
        {
            if (form != null)
            {
                form.Export += form_Export;
                form.Closed += form_Closed;
                form.NewForm += form_NewForm;
                form.CopyRows += form_CopyRows;
                form.PasteRows += new EventHandler<ExportEventArgs>(form_PasteRows);
                Forms.Add(form);
            }
        }

        void form_PasteRows(object sender, ExportEventArgs e)
        {
            if (Data != null)
            {
                var insertedForm = (MainForm) sender;
                Data = Rows.InsertCopiedRow(new SharedData() { GridView = insertedForm.workItemGridView, CopiedRows = Data.CopiedRows, GroupIndexer = insertedForm.Data.GroupIndexer, StepsCollection = insertedForm.Data.StepsCollection, TestProject = insertedForm.Data.TestProject, TestWorkItem = insertedForm.Data.TestWorkItem, TfsProjectCollection = insertedForm.Data.TfsProjectCollection,WorkItemAttributes = insertedForm.Data.WorkItemAttributes, WorkItemID = insertedForm.Data.WorkItemID});
            }
        }

        void form_CopyRows(object sender, ExportEventArgs e)
        {
            Data = Rows.Copy(e.Data);
        }

        void form_NewForm(object sender, EventArgs e)
        {
            var childForm = LoadData.NewMainForm();
            InitForm(childForm);
        }

        void form_Closed(object sender, EventArgs e)
        {
            Forms.Remove((MainForm) sender);
            if (Forms.Count == 0)
                this.Close();
        }

        void form_Export(object sender, ExportEventArgs e)
        {
            var childForm = Rows.Export(e.Data);
            InitForm(childForm);
        }

    }
}
